package com.taotao.service;

import com.alibaba.fastjson.JSONObject;
import com.taotao.config.ServerConfig;
import com.taotao.config.SwCloudConfig;
import com.taotao.utils.HttpClientUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author wangjin
 * @title: RegisterService
 * @projectName sw-springcloud
 * @description:
 * @date 2021/10/28 22:36
 */
public class RegisterService {
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private SwCloudConfig swCloudConfig;
    private static final Log log = LogFactory.getLog(RegisterService.class);
    @Autowired
    private ServiceRenewal serviceRenewal;

    public void register() {
        JSONObject data = requestParameter();
        // 4.使用httpclient技术发送请求注册
        while (true) {
            JSONObject result = HttpClientUtils.httpPost(swCloudConfig.getServerRegisterUrl() + "/sw/register", data);
            log.info("服务注册结果：" + result);
            if (result != null && result.getInteger("code") == 200) {
                serviceRenewal.start();
                return;
            }
            log.info("服务注册失败..开始重试策略");
            //为了避免cpu飙高的问题 设置重试次数
        }
    }

    public void remove() {
        JSONObject data = requestParameter();
        // 4.使用httpclient技术发送请求 服务地址删除
        JSONObject result = HttpClientUtils.httpPost(swCloudConfig.getServerRegisterUrl() + "/sw/remove", data);
        log.info("服务下线的结果：" + result);
    }

    public JSONObject requestParameter() {
        return requestParameter(null);
    }

    public JSONObject requestParameter(Long renewalDuration) {
        // 1.获取ip和端口号码
        String appHostAndPort = serverConfig.getAppHostAndPort();
        // 2. sericeName 服务的名称
        String serviceName = swCloudConfig.getServiceName();
        //3.注册中心url地址
        String serverRegisterUrl = swCloudConfig.getServerRegisterUrl();
        JSONObject data = new JSONObject();
        data.put("serviceName", serviceName);
        data.put("serviceAddres", appHostAndPort);
        if (renewalDuration != null) {
            data.put("renewalDuration", renewalDuration);
        }
        return data;
    }

    /**
     * 发送rest请求达到注册中心  服务续约
     */
    public void renewal() {
        JSONObject data = requestParameter(5000L);
        // 4.使用httpclient技术发送请求 服务地址删除
        JSONObject result = HttpClientUtils.httpPost(swCloudConfig.getServerRegisterUrl() + "/sw/renewal", data);
        log.info("服务续约结果：" + result);
    }
}
